package com.kangfu.api.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.kangfu.api.interceptor.AuthorizationInterceptor;
import com.kangfu.api.service.IAliyunSmsService;
import com.kangfu.api.service.IQiniuService;
import com.kangfu.common.annotation.IgnoreAuth;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.common.utils.RedisUtils;
import com.kangfu.db.mapper.MessageMapper;
import com.kangfu.db.mapper.NoticeMapper;
import com.kangfu.db.mapper.UserMapper;
import com.kangfu.db.model.request.SendSmsRequest;
import com.kangfu.db.model.request.UpdatePhoneRequest;
import com.kangfu.db.model.request.UserInfoRequest;
import com.kangfu.db.model.vo.UserVo;
import com.kangfu.api.service.ICheckinRecordService;
import com.kangfu.api.service.IUserService;
import com.kangfu.common.model.AjaxResult;
import com.kangfu.db.domain.entity.User;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public ICheckinRecordService checkinRecordService;

    @Autowired
    public IAliyunSmsService aliyunSmsService;

    @Autowired
    public IQiniuService qiniuService;

    @Autowired
    public NoticeMapper noticeMapper;

    @Autowired
    public MessageMapper messageMapper;


    /**
     * 更新用户手机号
     * @param userId
     * @return
     */
    @PostMapping("/updatePhone")
    public AjaxResult updatePhone (@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestBody UpdatePhoneRequest updatePhoneRequest) {
        userService.updateUserPhone(updatePhoneRequest.getCode(), userId);
        return AjaxResult.success();
    }

    /**
     * 更新用户头像和昵称
     * @param userId
     * @param userInfoRequest
     * @return
     */
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestBody UserInfoRequest userInfoRequest) {
        userService.updateUser(userId, userInfoRequest);
        return AjaxResult.success();
    }

    /**
     * 发送短信验证码
     * @param userId
     * @return
     */
    @PostMapping("/sendSms")
    public AjaxResult sendSms(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestBody SendSmsRequest sendSmsRequest) {
//        if (!Validator.isMobile(phone)) {
//            throw new BusinessException("请输入正确的手机号");
//        }
        String phone = sendSmsRequest.getPhone();
        if (phone == null) {
            throw new BusinessException("请输入手机号");
        }
        String code = String.valueOf(RandomUtil.randomInt(100000,999999));
        aliyunSmsService.sendSMS(phone,code);
        return AjaxResult.success();
    }

    /** 弃用 **/
    @PostMapping("/uploadAvatar")
    @CrossOrigin
    public AjaxResult uploadAvatar(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestParam( value = "file", required = false ) MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);

        String url = qiniuService.upload(in);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("url", url);
        return AjaxResult.success(hashMap);
    }

    @PostMapping("/uploadImg")
    @CrossOrigin
    public AjaxResult uploadImg(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestParam( value = "file", required = false ) MultipartFile file, @RequestParam(name = "type", defaultValue = "1") int type) throws IOException {
        byte[] bytes = file.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);

        String url = qiniuService.uploadByType(in, userId, type);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("url", url);
        return AjaxResult.success(hashMap);
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId) {
        User user = userService.selectUserById(userId);
        UserVo userVo = new UserVo();
        if (user != null) {
            userVo.setAvatar(user.getAvatar());
            userVo.setBindFlag(user.getBindFlag());
            userVo.setCheckinCount(user.getCheckinCount());
            userVo.setGoonCount(user.getGoonCount());
            userVo.setNickname(user.getNickname());
            userVo.setOpenid(user.getOpenid());
            if (!StrUtil.isBlank(user.getPhone())) {
                userVo.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
            } else {
                userVo.setPhone("");
            }
            userVo.setSex(user.getSex());
            int age = 0;
            if (user.getBirthday() != null) {
                age = (int)ChronoUnit.YEARS.between(user.getBirthday(), LocalDate.now());
            }
            userVo.setVersion(user.getVersion());
            userVo.setAge(age);
            userVo.setBirthday(user.getBirthday());
            userVo.setArea(user.getArea());
            userVo.setAddress(user.getAddress());
            userVo.setAreaCode(user.getAreaCode());
            //累计打卡超越人数
            int exceedCount = userMapper.selectExceedCount(user.getCheckinCount());
            userVo.setExceedCount(exceedCount);  //累计打卡超越人数
            //检查用户的华为授权是否完整
            userVo.setHuaweiAuthorizeComplete(user.getHuaweiAuthorizeComplete());
        }
        return AjaxResult.success(userVo);
    }


    @GetMapping("/getUnreadCount")
    public AjaxResult getUnreadCount(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId) {
        Integer noticeUnreadCount = noticeMapper.selectUnreadCount(userId);
        Integer messageUnreadCount = messageMapper.selectUnreadCountByUserId(userId);
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("noticeUnreadCount",noticeUnreadCount);
        hashMap.put("messageUnreadCount",messageUnreadCount);
        return AjaxResult.success(hashMap);
    }


    @GetMapping("/getSportsCycle")
    public AjaxResult getSportsCycle(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId) {
        User user = userService.selectUserById(userId);
        //获取手术时间
        LocalDateTime operationTime = user.getOperationTime();
        //看看是术后第几周
        int week = 1;  //没做手术默认是第一周
        if (operationTime != null) {
            long betweenDay = LocalDateTimeUtil.between(LocalDateTimeUtil.beginOfDay(operationTime), LocalDateTimeUtil.beginOfDay(LocalDateTime.now()), ChronoUnit.DAYS);
            week = (int)Math.ceil((double)(((int)betweenDay-1)/7)) + 1;
        }
        int level = 1;
        if (week <= 1) {
            level = 1;
        } else if (week >=2 && week <= 3) {
            level = 2;
        } else if (week >=4 && week <= 6) {
            level = 3;
        } else if (week >=7 && week <= 8) {
            level = 4;
        } else if (week == 9) {
            level = 5;
        } else if (week >= 10) {
            level = 6;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("level",level);
        return AjaxResult.success(hashMap);

    }



}
